<?php
/**
 * Created by PhpStorm.
 * User: DR
 * Date: 2018/8/5
 * Time: 14:21
 */

namespace app\api\model;


use fast\Http;
use think\Db;
use think\exception\ValidateException;

class Deal extends BaseModel
{
    protected $hidden = ['id', 'pay_status'];//'type',

    //付款状态
    public static function payStatus($order_sn,$user,$buy_remark = '')
    {
        $order = Order::get(['order_sn' => $order_sn,'buy_user_id'=>$user->id]);
        if (!$order ) {
            throw new ValidateException('订单不存在!');
        }
        $order->pay_time = time();
        $order->status = 2;
        $order->buy_remark = $buy_remark;
        if ($order->save()) {
            return true;
        } else {
            return false;
        }
    }

//    public static function confirmStatus($deal_sn)
//    {
//        $orderModel = new Order();
//        $dealModel = new Deal();
//        $order = $orderModel
//            ->whereOr('buy_deal_sn',$deal_sn)
//            ->whereOr('sale_deal_sn',$deal_sn)
//            ->select();
//        $order->status = 3;
//        $order->complete_time = time();
//        $order->save();
//        $order1 = $orderModel
//            ->where(['buy_deal_sn'=>$order->buy_deal_sn,'status'=>['<>',3]])
//            ->find();
//        if($order1) {
//            $deal = $dealModel->where('deal_sn',$order->sale_deal_sn)->find();
//            $deal->status = 3;
//            $deal->save();
//        }
//        $order2 = $orderModel
//            ->where(['sale_deal_sn'=>$order->sale_deal_sn,'status'=>['<>',3]])
//            ->find();
//        if($order2)
//        {
//            $deal = $dealModel->where('deal_sn',$order->buy_deal_sn)->find();
//            $deal->status = 3;
//            $deal->save();
//        }
//    }




    //确认付币
    public static function confirmStatus($order_sn)
    {
        $order = Order::get(['order_sn' => $order_sn]);
        if (!$order || $order->status != 2) {
            throw new ValidateException('订单不存在或无法确认付币!');
        }
        $order->complete_time = time();
        $order->status = 3;
        $order->save();
        $dealModel = new Deal();
        $orderModel = new Order();
        if ($order['type'] == '1') {        //卖为主
            $buy_deal = $dealModel->where('deal_sn',$order->buy_deal_sn)->find();       //需要付币的订单
            $user_id = $dealModel->where('deal_sn',$order->sale_deal_sn)->field('user_id')->find(); //卖家ID
            self::salePayCNY($buy_deal,$user_id['user_id']);
            //搜索卖单交易号
            $map['sale_deal_sn'] = $order->sale_deal_sn;
            $map['status'] = ['<>', 3];
            $orders = $orderModel->where($map)->find();         //如果找到不为3=完成的就直接返回  只更改了当前一条订单状态
            if ($orders) {
                $dealModel->where('deal_sn',$order->buy_deal_sn)->update(['status'=>3,'complate_time'=>time()]);
                return true;
            } else {                                            //如果找不到就搜索全部
                $orders = $orderModel
                    ->whereOr('buy_deal_sn', $order->buy_deal_sn)
                    ->whereOr('sale_deal_sn', $order->sale_deal_sn)
                    ->select();
                $sn = '';                                       //拼接字符串
                foreach ($orders as $value) {
                    if (!strstr($sn, $value->buy_deal_sn)) {
                        $sn .= $value->buy_deal_sn . ',';
                    }
                    if (!strstr($sn, $value->sale_deal_sn)) {
                        $sn .= $value->sale_deal_sn . ',';
                    }
                }
                $sn = rtrim($sn, ",");                  //删除最后的,
                $dealModel->where('deal_sn','in',$sn)->update(['status'=>3,'complate_time'=>time()]);       //统一更新
                return true;
            }
        } else {                //买为主
            $sale_deal = $dealModel->where('deal_sn',$order->sale_deal_sn)->find();       //需要付币的订单
            $user_id = $dealModel->where('deal_sn',$order->buy_deal_sn)->field('user_id')->find(); //买家ID
            self::salePayCNY($sale_deal,$user_id['user_id']);
            //搜索买单交易号
            $map['buy_deal_sn'] = $order->buy_deal_sn;
            $map['status'] = ['<>', 3];
            $orders = $orderModel->where($map)->find();         //如果找到不为3=完成的就直接返回  只更改了当前一条订单状态
            if ($orders) {
                $dealModel->where('deal_sn',$order->sale_deal_sn)->update(['status'=>3,'complate_time'=>time()]);
                return true;
            } else {                                            //如果找不到就搜索全部
                $orders = $orderModel
                    ->whereOr('buy_deal_sn', $order->buy_deal_sn)
                    ->whereOr('sale_deal_sn', $order->sale_deal_sn)
                    ->select();
                $sn = '';                                       //拼接字符串
                foreach ($orders as $value) {
                    if (!strstr($sn, $value->buy_deal_sn)) {
                        $sn .= $value->buy_deal_sn . ',';
                    }
                    if (!strstr($sn, $value->sale_deal_sn)) {
                        $sn .= $value->sale_deal_sn . ',';
                    }
                }
                $sn = rtrim($sn, ",");                  //删除最后的,
                $dealModel->where('deal_sn','in',$sn)->update(['status'=>3,'complate_time'=>time()]);       //统一更新
                return true;
            }
        }
        return false;
    }

    public static function salePayCNY($deal,$sale_user_id)       //卖为主付币
    {
        $cny = $deal->cny;
        $buy_user_id = $deal->user_id;
        $userModel = new \app\admin\model\User();
        $buy_user = $userModel->where('id',$buy_user_id)->find();
        $sale_user = $userModel->where('id',$sale_user_id)->find();
        $buy_user->cny += $cny;                                         //增加买方用户cny
        $buy_user->total_cny += $cny;                                   //增加买方用户总cny
        $buy_user->save();
        account_log(                                                    //记录资金流动
            $buy_user->id,
            $cny,
            $buy_user->cny + $buy_user->freeze_cny,
            '',
            $buy_user->sac,
            '卖家ID:'.$sale_user->id.'成功付币',
            '',
            $deal->deal_sn
            );
        $sale_user->freeze_cny -= $cny;
        $sale_user->save();
        account_log(
          $sale_user->id,
          '',
          $sale_user->cny + $sale_user->freeze_cny,
          '',
          $sale_user->sac,
          '给买家ID:'.$buy_user->id.'付币',
          $cny*-1,
          $deal->deal_sn
        );
    }

    public static function buyPayCNY($deal,$buy_user_id)        //买为主付币
    {
        $cny = $deal->cny;
        $sale_user_id = $deal->user_id;
        $userModel = new \app\admin\model\User();
        $sale_user = $userModel->where('id',$sale_user_id)->find();
        $buy_user = $userModel->where('id',$buy_user_id)->find();
        $buy_user->cny += $cny;
        $buy_user->total_cny += $cny;
        $buy_user->save();
        account_log(                                                    //记录资金流动
            $buy_user->id,
            $cny,
            $buy_user->cny + $buy_user->freeze_cny,
            '',
            $buy_user->sac,
            '卖家ID:'.$sale_user->id.'付币',
            '',
            $deal->deal_sn
        );
        $sale_user->freeze_cny -= $cny;
        $sale_user->save();
        account_log(
            $sale_user->id,
            '',
            $sale_user->cny + $sale_user->freeze_cny,
            '',
            $sale_user->sac,
            '给买家ID:'.$buy_user->id.'付币',
            $cny*-1,
            $deal->deal_sn
        );
    }


//    public static function changeDealStatus($user, $order_sn, $status)
//    {
//        $order = new \app\common\model\Order();
//        $order_where = ['order_sn'  =>  $order_sn];
//        $order_info = $order->where($order_where)->find();  //  order表的记录
//
//        if (!$order_info)
//        {
//            throw new ValidateException('订单不存在');
//        }
//
//        //  判断 买/卖 为主,修改主状态
//        if ($order_info->type == config('DealType.Buy'))
//        {
//            //  修改副状态
//            $deal = new \app\admin\model\Deal();
//            $deal_info = $deal
//                ->where(['deal_sn' => $order_info->sale_deal_sn])
//                ->find();
//            if (!$deal_info)
//            {
//                throw new ValidateException('挂单不存在');
//            }
//            $deal_info->save(['status' => $status]);    //  修改交易记录状态
//
//            //  遍历决定是否修改主状态
//            $orders = $order->where(['buy_deal_sn'   =>  $order_info->buy_deal_sn])->select();
//            $all_right = false;
//            foreach ($orders as $item)
//            {
//                //  遍历所有卖家
//                $tmp_deal = $deal->where([
//                    'deal_sn'   =>  $item->sale_deal_sn,
//                    'status'    =>  ['<>' , $status]
//                ])->find();
//                if ($tmp_deal)
//                {
//                    $all_right = true;
//                }
//            }
//            if ($all_right)
//            {
//                //  如果全部状态都改变,则修改主状态
//                $deal->where(['deal_sn' => $order_info->buy_deal_sn])->update(['status' => $status]);
//            }
//        }
//        else{
//            //  修改副状态
//            $deal = new \app\admin\model\Deal();
//            $deal_info = $deal
//                ->where(['deal_sn' => $order_info->buy_deal_sn])
//                ->find();
//            if (!$deal_info)
//            {
//                throw new ValidateException('挂单不存在');
//            }
//            $deal_info->save(['status' => $status]);    //  修改交易记录状态
//
//            //  遍历决定是否修改主状态
//            $orders = $order->where(['sale_deal_sn'   =>  $order_info->sale_deal_sn])->select();
//            $all_right = false;
//            foreach ($orders as $item)
//            {
//                //  遍历所有买家
//                $tmp_deal = $deal->where([
//                    'deal_sn'   =>  $item->buy_deal_sn,
//                    'status'    =>  ['<>' , $status]
//                ])->find();
//                if ($tmp_deal)
//                {
//                    $all_right = true;
//                }
//            }
//            if ($all_right)
//            {
//                //  如果全部状态都改变,则修改主状态
//                $deal->where(['deal_sn' => $order_info->buy_deal_sn])->update(['status' => $status]);
//            }
//        }
//
//        return true;
//    }

//    public static function changeDealStatus_bak($user, $deal_sn, $status)
//    {
//        $deal_info = self::get([['deal_sn' => $deal_sn],['user_id' => $user->id]]);
//        if (!$deal_info)
//        {
//            throw new ValidateException('挂单不存在或者不属于当前用户');
//        }
//        //  修改deal状态
//        $deal_info->status = $status;
//
//        if ($deal_info->type == config('DealType.Buy'))
//        {
//            //  买
//            $order = new \app\common\model\Order();
//            $order_info = \app\common\model\Order::get(['buy_deal_sn' => $deal_sn]);
//            if (!$order_info)
//            {
//                throw new ValidateException('订单不存在');
//            }
//            $order_sn = '';
//            if ($order_info->type == config('DealType.Buy'))
//            {
//                //$order_sn = $order_info->buy_deal_sn;
//                //  查找所有同一交易下的订单
//                $orders = $order->where('buy_deal_sn','=',$order_info->buy_deal_sn)->select();
//                foreach ($orders as $item)
//                {
////                    if ($orders->)
//                }
//            }
//            else{
//                $order_sn = $order_info->sale_deal_sn;
//            }
//
//
//
//        }
//        else{
//
//        }
//
//    }

    /*
     * 处理订单状态
     * @param int $status 0=取消,1=确认付款,2=确认收款并付币
     */
//    public static function changeDealStatus_bak($user, $deal_sn, $status)
//    {
//        $deal = self::get(['deal_sn' => $deal_sn]);
//        if ($deal->user_id != $user->id) {
//            throw new ValidateException('当前挂单不属于该用户');
//        }
//        if ($status == 0) {
//            if ($deal->status != '未交易') {
//                throw new ValidateException('当前订单不能取消');
//            }
//            $deal->status = 0;
//            $deal->save();
//            return true;
//        }else{
//            if($deal->status != '交易中'){
//                throw new ValidateException('当前订单无法付款');
//            }
//            if($status == 1){
//                $deal->pay_status = 1;
//                $deal->pay_time = time();
//                self::changeOrderStatus($deal);
//            }
//            if($status == 2)
//            {
//                if($deal->pay_status != '1'){
//                    throw new ValidateException('当前订单未付款,无法确认');
//                }
//                $deal->pay_status = 2;
//                $deal->status = 3;
//                $deal->complate_time = time();
//                self::changeOrderStatus($deal);
//            }
//            $deal->save();
//            return true;
//        }
//        return false;
//
//    }

    /*
     * 根据挂单状态判断订单状态
     */
    public static function changeOrderStatus($deal)
    {
        if ($deal->type) {
            $where['sale_deal_sn'] = $deal->deal_sn;
        } else {
            $where['buy_deal_sn'] = $deal->deal_sn;
        }
        $order = Order::get($where);
        $order->pay_time = time();
        $order->save();
    }

    /*
     * 生成挂单
     */
    public static function makeDeal($user, $data)
    {
        $cny = $data['cny'];
        $type = $data['type'];
        $deal_sn = generate_deal_id($cny);
        $deal = [
            'deal_sn' => $deal_sn,
            'cny' => $cny,
            'type' => $type,
            'status' => 1,
            'create_time' => time(),
            'user_id' => $user->id,
            'residue_cny' => $cny,
            'remark'    =>  $data['remark']
        ];
        if ($type == 1) {
            parent::checkUserCny($user, $cny);
            parent::dealUserMoney($user, $cny, true);
            account_log(
                $user->id,
                $cny * -1,
                $user->cny + $user->freeze_cny,
                '',
                $user->sac,
                '挂卖单,卖出CNY:' . $cny,
                $cny,
                $deal_sn
            );
        }
        self::insert($deal);
    }

    public function getCreateTimeAttr($value, $data)
    {
        return $this->getDateTime($value, $data);
    }

//    public function getStatusAttr($value, $data)
//    {
//        $status = [
//            0 => '已取消',
//            1 => '未交易',
//            2 => '交易中',
//            3 => '已完成'
//        ];
//        return $status[$value];
//    }
}